package com.xhwl.centiotdata.suppliersystem.yaoan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.YaoAnConstant;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.YaoAnVRRecordDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.utils.Base64Utils;
import com.xhwl.centiotdata.utils.HttpUtils;
import com.xhwl.centiotdata.utils.LocalDateTimeUtils;
import com.xhwl.common.dto.cent.visitor.VisitorAuthDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.government.EmployeeVRExperienceDetail;
import com.xhwl.common.pojo.cent.visitor.yaoan.VisitorVRExperienceDetail;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author tangwei
 * @description 访客对接耀安
 * @create 2022-11-14 18:00
 */
@Slf4j
@Service
public class VisitorYaoAnHandler {

    @Autowired
    private IDeviceCentService iDeviceCentService;

    // 新增访客数据
    public void createUser(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO authDTO) throws Exception {
        ProductAccessQuery productAccessQuery = new ProductAccessQuery();
        productAccessQuery.setProjectId(configDTO.getProjectId());
        productAccessQuery.setCategoryId(CategoryEnum.VISITOR_SYSTEM.getId());
        List<DeviceProjSupplierCategory> deviceConfigList = iDeviceCentService.listProductAccess(null, productAccessQuery);
        deviceConfigList = deviceConfigList.stream().filter(item -> item.getProductId().equals(ProductEnum.YAOAN_VR.getId())).collect(Collectors.toList());
        JSONObject properties = deviceConfigList.get(0).getProperties();
        log.info("获取的访客VR集成配置:{}", properties);
        if (Objects.nonNull(properties)) {
            Map<String, String> body = new HashMap<>();
            body.put("lsLaborsKey", authDTO.getIdentityCard());
            body.put("deptCode", properties.getString("deptCode"));
            body.put("laHeadPic", "data:image/jpeg;base64," + Base64Utils.imageUrlToBase64(authDTO.getFaceUrl()));
            body.put("laIdCard", authDTO.getIdentityCard());
            body.put("laName", authDTO.getName());
            body.put("laPhone", authDTO.getPhone());
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            HttpResponse response = HttpUtils.doPost(configDTO.getIpAndPort(), YaoAnConstant.ADD_VISITOR, null, headers,
                    new HashMap<>(), "[" + JSONObject.toJSONString(body) + "]");
            if (200 != response.getStatusLine().getStatusCode()) {
                throw new BusinessException("请求耀安系统异常:code=" + response.getStatusLine().getStatusCode());
            }
        }
    }

    // 获取VR数据
    public List<YaoAnVRRecordDTO> getRecord(VisitorIntegrationConfigDTO configDTO, String deptCode) throws Exception {
        Map<String, String> body = new HashMap<>();
        String resultCode = String.valueOf(YaoAnConstant.RESULT_CODE);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        HttpResponse response = HttpUtils.doPost(configDTO.getIpAndPort(), YaoAnConstant.VR_RECORD, null, headers,
                new HashMap<>(), JSONObject.toJSONString(body));
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new BusinessException("请求耀安系统异常:code=" + response.getStatusLine().getStatusCode());
        }
        HttpEntity resEntity = response.getEntity();
        List<YaoAnVRRecordDTO> visitorVRExperiences = new ArrayList<>();
        if (resEntity != null) {
            String res = EntityUtils.toString(resEntity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(res);
            if (jsonObject != null && resultCode.equals(jsonObject.getString("result"))) {
                JSONArray dataJsonArray = jsonObject.getJSONArray("list");
                if (dataJsonArray != null && !dataJsonArray.isEmpty()) {
                    for (Object objJson : dataJsonArray) {
                        JSONObject jsonOb = (JSONObject) objJson;
                        YaoAnVRRecordDTO dto = new YaoAnVRRecordDTO();
                        if (!deptCode.equals(jsonOb.getString("deptCode"))) {
                            dto.setLsLaborsKey(jsonOb.getInteger("lsLaborsKey"));
                        }
                        dto.setName(jsonOb.getString("name"));
                        dto.setIdCard(jsonOb.getString("idCard"));
                        dto.setPassTime(LocalDateTimeUtils.getStrCoverDate(jsonOb.getString("passTime"), LocalDateTimeUtils.DATE_TIME));
                        dto.setNum(jsonOb.getInteger("num"));
                        dto.setDeptCode(jsonOb.getString("deptCode"));
                        visitorVRExperiences.add(dto);
                    }
                }
            }
        }
        return visitorVRExperiences;
    }

    // 获取访客VR详情数据
    public List<VisitorVRExperienceDetail> getVisitorDetailList(VisitorIntegrationConfigDTO configDTO, String idCard) throws Exception {
        Map<String, String> param = new HashMap<>();
        String resultCode = String.valueOf(YaoAnConstant.RESULT_CODE);
        param.put("idCard", idCard);
        HttpResponse response = HttpUtils.doGet(configDTO.getIpAndPort(), YaoAnConstant.VR_RECORD_DETAIL, null, new HashMap<>(), param);
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new BusinessException("请求耀安系统异常:code=" + response.getStatusLine().getStatusCode());
        }
        HttpEntity resEntity = response.getEntity();
        String res;
        List<VisitorVRExperienceDetail> visitorVRExperienceDetails = new ArrayList<>();
        if (resEntity != null) {
            res = EntityUtils.toString(resEntity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(res);
            if (jsonObject != null && resultCode.equals(jsonObject.getString("result"))) {
                JSONArray dataJsonArray = jsonObject.getJSONArray("list");
                if (dataJsonArray != null && !dataJsonArray.isEmpty()) {
                    for (Object objJson : dataJsonArray) {
                        JSONObject jsonOb = (JSONObject) objJson;
                        VisitorVRExperienceDetail dto = new VisitorVRExperienceDetail();
                        dto.setInfoId(jsonOb.getInteger("id"));
                        dto.setFaceMachineCode(jsonOb.getString("sn"));
                        dto.setName(jsonOb.getString("name"));
                        dto.setIdCard(jsonOb.getString("idCard"));
                        dto.setPass(jsonOb.getString("pass"));
                        dto.setPassTime(LocalDateTimeUtils.getStrCoverDate(jsonOb.getString("passTime"), LocalDateTimeUtils.DATE_TIME));
                        dto.setDoName(jsonOb.getString("doName"));
                        dto.setDoRegion(jsonOb.getString("doRegion"));
                        dto.setScore(jsonOb.getFloat("score"));
                        dto.setClassHour(jsonOb.getFloat("classHour"));
                        dto.setRemarks(jsonOb.getString("remarks"));
                        visitorVRExperienceDetails.add(dto);
                    }
                }
            }
        }
        return visitorVRExperienceDetails;
    }

    // 获取员工VR详情数据
    public List<EmployeeVRExperienceDetail> getEmployeeDetailList(VisitorIntegrationConfigDTO configDTO, String idCard, String deptCode) throws Exception {
        Map<String, String> param = new HashMap<>();
        String resultCode = String.valueOf(YaoAnConstant.RESULT_CODE);
        param.put("idCard", idCard);
        HttpResponse response = HttpUtils.doGet(configDTO.getIpAndPort(), YaoAnConstant.VR_RECORD_DETAIL, null, new HashMap<>(), param);
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new BusinessException("请求耀安系统异常:code=" + response.getStatusLine().getStatusCode());
        }
        HttpEntity resEntity = response.getEntity();
        String res;
        List<EmployeeVRExperienceDetail> employeeVRRecordDetailList = new ArrayList<>();
        if (resEntity != null) {
            res = EntityUtils.toString(resEntity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(res);
            if (jsonObject != null && resultCode.equals(jsonObject.getString("result"))) {
                JSONArray dataJsonArray = jsonObject.getJSONArray("list");
                if (dataJsonArray != null && !dataJsonArray.isEmpty()) {
                    for (Object objJson : dataJsonArray) {
                        JSONObject jsonOb = (JSONObject) objJson;
                        EmployeeVRExperienceDetail dto = new EmployeeVRExperienceDetail();
                        dto.setInfoId(jsonOb.getInteger("id"));
                        dto.setName(jsonOb.getString("name"));
                        dto.setIdCard(jsonOb.getString("idCard"));
                        dto.setPassTime(LocalDateTimeUtils.getStrCoverDate(jsonOb.getString("passTime"), LocalDateTimeUtils.DATE_TIME));
                        dto.setDoName(jsonOb.getString("doName"));
                        dto.setScore(jsonOb.getFloat("score"));
                        dto.setClassHour(jsonOb.getFloat("classHour"));
                        employeeVRRecordDetailList.add(dto);
                    }
                }
            }
        }
        return employeeVRRecordDetailList;
    }
}
